package cn.com.dhcc.turbo.web.controller.exch;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.Status;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.turbo.entity.exch.ExchRel;
import cn.com.dhcc.turbo.entity.exch.NodeLayout;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncOperType;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncType;
import cn.com.dhcc.turbo.service.exch.ExchRelService;
import cn.com.dhcc.turbo.service.registry.LocalConfCallBack;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
import cn.com.dhcc.turbo.service.registry.sync.SynchronizeHandler;

import com.thoughtworks.xstream.XStream;
/**
 * 关系管理
 * 
 * @日期：2014-8-6 上午10:27:45
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("/exch")
@TurboMenu(belongToMenu=LEAF_MENU.EXCH_REL_MGR)
public class ExchRelController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.TURBO);
	@Autowired
	private ExchRelService exchRelService;
	@Autowired
	private NodeInfoService nodeService;
	@Autowired
	SynchronizeHandler syncHandler;
	@Autowired
	LocalConfCallBack localConfCallBack;
	/**
	 * 交换关系管理
	 * @param model
	 * @param nodeId 节点id
	 * @return
	 */
	@RequestMapping(value = "/exch_rel_mgr")
	public String exchRelMgr(Model model){
		return "exch/exch_rel_mgr";
	}
	/**
	 * 建立交换关系
	 * @param model
	 * @param creatorId　发起节点id
	 * @param toId　接收节点id
	 * @return
	 */
	@RequestMapping(value = "/add_exch_rel", method = RequestMethod.POST)
	public void  addExchRel( Model model,HttpServletResponse response,String creatorId,String toId,String relNodeLayout) {
		try{
			//保存关系
			ExchRel vo = new ExchRel();
			vo.setNodeIdCreator(creatorId);
			vo.setNodeIdTo(toId);
			vo.setMtime(new Date());
			Status status = exchRelService.createRelAndSync(vo);
			NodeInfo localNode = nodeService.getLocalNode();
			if(status.isSuccess()){
				if(!localNode.getId().equals(vo.getNodeIdCreator())){
					NodeLayout layout = exchRelService.getNodeLayoutRelXML(vo.getNodeIdCreator());
					syncHandler.syncToNodeFromLocalNode(SyncType.FLEX_LAYOUT, nodeService.get(vo.getNodeIdCreator()), layout, SyncOperType.UPDATE,true);
				}
				if(!localNode.getId().equals(vo.getNodeIdTo())){
					NodeLayout layout = exchRelService.getNodeLayoutRelXML(vo.getNodeIdTo());
					syncHandler.syncToNodeFromLocalNode(SyncType.FLEX_LAYOUT, nodeService.get(vo.getNodeIdTo()), layout, SyncOperType.UPDATE,true);
				}
			}
			String res = "{\"msg\":\""+status.getMsg()+"\",\"status\":\""+status.isSuccess()+"\",\"fromNode\":\""+creatorId+"\",\"toNode\":\""+toId+"\"}";
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("text/html;charset=UTF-8");
			FileCopyUtils.copy(res, new OutputStreamWriter(outputStream, "UTF-8"));
			outputStream.flush();
			response.flushBuffer();
			if (outputStream != null)
				outputStream.close();
		} catch (Exception e) {
			logger.error("建立交换关系失败", e);
		}
		
	}
	
	/**
	 * 删除交换关系
	 * @param model
	 * @param creatorId　发起节点id
	 * @param toId　接收节点id
	 * @return
	 */
	@RequestMapping(value = "/del_line_exch_rel")
	public void  delLineExchRel(  Model model,HttpServletResponse response,String creatorId,String toId) {
		try {
			NodeInfo fromNode = nodeService.get(creatorId);
			NodeInfo toNode = nodeService.get(toId);
			Status status = localConfCallBack.onNodeExchRelRemove(fromNode, toNode);
			NodeInfo localNode = nodeService.getLocalNode();
			if(status.isSuccess()){
				if(!localNode.getId().equals(creatorId)){
					NodeLayout layout = exchRelService.getNodeLayoutRelXML(creatorId);
					syncHandler.syncToNodeFromLocalNode(SyncType.FLEX_LAYOUT, nodeService.get(creatorId), layout, SyncOperType.UPDATE,true);
				}
				if(!localNode.getId().equals(toId)){
					NodeLayout layout = exchRelService.getNodeLayoutRelXML(toId);
					syncHandler.syncToNodeFromLocalNode(SyncType.FLEX_LAYOUT, nodeService.get(toId), layout, SyncOperType.UPDATE,true);
				}
			}
			String res = "{\"msg\":\""+status.getMsg()+"\",\"status\":\""+status.isSuccess()+"\",\"fromNode\":\""+creatorId+"\",\"toNode\":\""+toId+"\"}";
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("text/html;charset=UTF-8");
			FileCopyUtils.copy(res, new OutputStreamWriter(outputStream, "UTF-8"));
			outputStream.flush();
			response.flushBuffer();
			if (outputStream != null)
				outputStream.close();
		} catch (Exception e) {
			logger.error("删除交换关系失败", e);
		}
	}
	/**
	 * 当关系图删除一个节点时，删除它的所有交换关系
	 * @param model
	 * @param nodeId
	 */
	@RequestMapping(value = "/del_node_exch_rel")
	public void  delNodeExchRel( Model model,String nodeId) {
		try {
			List<ExchRel> list = exchRelService.getAllExchByNodeId(nodeId);
			NodeInfo localNode = nodeService.getLocalNode();
//			NodeLayout nodeLayout = exchRelService.getNodeLayout(localNode.getId());
			exchRelService.delExchRelByNodeId(nodeId);
			exchRelService.delNodeRelLayout(nodeId);
			for(int i = 0 ; i < list.size() ; i++){
				ExchRel rel = list.get(i);
				if(!localNode.getId().equals(rel.getNodeIdCreator())){
					NodeLayout layout = exchRelService.getNodeLayoutRelXML(rel.getNodeIdCreator());
					syncHandler.syncToNodeFromLocalNode(SyncType.FLEX_LAYOUT, nodeService.get(rel.getNodeIdCreator()), layout, SyncOperType.UPDATE,true);
				}
				if(!localNode.getId().equals(rel.getNodeIdTo())){
					NodeLayout layout = exchRelService.getNodeLayoutRelXML(rel.getNodeIdTo());
					syncHandler.syncToNodeFromLocalNode(SyncType.FLEX_LAYOUT, nodeService.get(rel.getNodeIdTo()), layout, SyncOperType.UPDATE,true);
				}
			}
		} catch (Exception e) {
			logger.error("删除交换关系失败", e);
		}
	}
	/**
	 * 节点信息
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/get_node")
	public void getNode(Model model,HttpServletResponse response,String nodeId) {
		try {
			NodeInfo vo;
			if("".equals(nodeId) || nodeId == null){
				 vo = nodeService.getLocalNode();
			}else{
				vo = nodeService.get(nodeId);
			}
			//封装xml格式数据
			XStream xstream = new XStream();
			xstream.alias("node", NodeInfo.class);
			String  rstVal = xstream.toXML(vo);
			//结果数据输出
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("text/xml;charset=UTF-8");
			FileCopyUtils.copy(rstVal, new OutputStreamWriter(outputStream, "UTF-8"));
			outputStream.flush();
			response.flushBuffer();
			if (outputStream != null)
				outputStream.close();
		} catch (Exception e) {
			logger.error("获取节点信息失败", e);
		}
	}
	/**
	 * 树初始化
	 * @param model
	 * @param response
	 */
	@RequestMapping(value = "/exch_node_tree_init")
	public void treeInit(Model model,HttpServletResponse response) {
		try {
			String  rstVal = exchRelService.getRootNodeTree();
			//结果数据输出
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("text/xml;charset=UTF-8");
			FileCopyUtils.copy(rstVal, new OutputStreamWriter(outputStream, "UTF-8"));
			outputStream.flush();
			response.flushBuffer();
			if (outputStream != null)
				outputStream.close();
		} catch (Exception e) {
			logger.error("获取节点信息失败", e);
		}
	}
	/**
	 * 树点击　动态加载
	 * @param model
	 * @param response
	 * @param id 节点id
	 */
	@RequestMapping(value = "/exch_node_tree")
	public void nodeTree(Model model,HttpServletResponse response,String nodeId) {
		try {
			String  rstVal = exchRelService.nodeTree(nodeId);
			//结果数据输出
			rstVal = "<TreeView>" +rstVal+"</TreeView>";
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("text/xml;charset=UTF-8");
			FileCopyUtils.copy(rstVal, new OutputStreamWriter(outputStream, "UTF-8"));
			outputStream.flush();
			response.flushBuffer();
			if (outputStream != null)
				outputStream.close();
		} catch (Exception e) {
			logger.error("获取节点信息失败", e);
		}
	}
	/**
	 * 获取交换关系图
	 * @param model
	 * @param response
	 * @param nodeId
	 */
	@RequestMapping(value = "/get_node_layout")
	public void getNodeLayout(Model model,HttpServletResponse response,String nodeId) {
		try {
			NodeInfo localNode = nodeService.getLocalNode();
			NodeLayout nodeLayout = exchRelService.getNodeLayout(localNode.getId());
			if(nodeLayout != null){
				String  rstVal  = "";
				if(localNode.getId().equals(nodeId) || "".equals(nodeId) || nodeId ==null){
					rstVal = exchRelService.forExchRelXMLAllNode(nodeLayout.getRelNodeLayout());
				}else{
					rstVal = exchRelService.forExchRelXML(nodeLayout.getRelNodeLayout(),nodeId);
				}
				//结果数据输出
				OutputStream outputStream = response.getOutputStream();
				response.setContentType("text/xml;charset=UTF-8");
				FileCopyUtils.copy(rstVal, new OutputStreamWriter(outputStream, "UTF-8"));
				outputStream.flush();
				response.flushBuffer();
				if (outputStream != null)
					outputStream.close();
			}
			
		} catch (Exception e) {
			logger.error("获取节点信息失败", e);
		}
	}
	@RequestMapping(value = "/add_node_layout")
	public void addNodeLayout(Model model,String relNodeLayout){
		try {
			NodeInfo node = nodeService.getLocalNode();
			NodeLayout vo = exchRelService.getNodeLayout(node.getId());
			if( vo != null){
				vo.setRelNodeLayout(relNodeLayout);
				exchRelService.updateNodeLayout(vo);
			}else{
				vo = new NodeLayout();
				vo.setId(UUIDGenerator.getUUID());
				vo.setNodeId(node.getId());
				vo.setRelNodeLayout(relNodeLayout);
				vo.setMtime(new Date());
				exchRelService.addNodeLayout(vo);
			}
		} catch (ServiceException e) {
			logger.error("保存交换关系图失败", e);
		}
	}
	/**
	 * 保存关系图，同步关系图（对交换关系操作）
	 * @param model
	 * @param relNodeLayout
	 */
	@RequestMapping(value = "/sync_node_layout")
	public void syncNodeLayout(Model model,String relNodeLayout,String fromNode,String toNode){
		try {
			NodeInfo localNode = nodeService.getLocalNode();
			NodeLayout vo = exchRelService.getNodeLayout(localNode.getId());
			if( vo != null){
				vo.setRelNodeLayout(relNodeLayout);
				exchRelService.updateNodeLayout(vo);
			}else{
				vo = new NodeLayout();
				vo.setId(UUIDGenerator.getUUID());
				vo.setNodeId(localNode.getId());
				vo.setRelNodeLayout(relNodeLayout);
				vo.setMtime(new Date());
				exchRelService.addNodeLayout(vo);
			}
			if(!localNode.getId().equals(fromNode)){
				NodeLayout layout = exchRelService.getNodeLayoutRelXML(fromNode);
				syncHandler.syncToNodeFromLocalNode(SyncType.FLEX_LAYOUT, nodeService.get(fromNode), layout, SyncOperType.UPDATE,true);
			}
			if(!localNode.getId().equals(toNode)){
				NodeLayout layout = exchRelService.getNodeLayoutRelXML(toNode);
				syncHandler.syncToNodeFromLocalNode(SyncType.FLEX_LAYOUT, nodeService.get(toNode), layout, SyncOperType.UPDATE,true);
			}
		} catch (Exception e) {
			logger.error("保存交换关系图失败", e);
		}
	}
}
